import { login, logout, getInfo } from '@/api/user'
import { getTokenCookies, setTokenCookies, removeTokenCookies, getTokenSessionStorage, setTokenSessionStorage, removeTokenSessionStorage } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getTokenSessionStorage() || getTokenCookies(),
  name: '',
  userId: '',
  introduction: '',
  roles: 0,
  stationIds: [],
  org: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ORG: (state, org) => {
    state.org = org
  },
  SET_STATIONIDS: (state, stationIds) => {
    state.stationIds = stationIds
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { userName, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: userName.trim(), password: password })
        .then(response => {
          if(response.code == 0){
            const { data } = response
            data.token=data.userId // 20230301 
            commit('SET_TOKEN', data.token) 
            setTokenCookies(data.token)
            setTokenSessionStorage(data.token)
            resolve()
          }
          else{
            reject(response.msg)
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit}, userId) {
    return new Promise((resolve, reject) => {
      getInfo({userId:userId}).then(response => {
          const { data } = response
          if (!data) {
            reject('验证失败，请重新登录')
          }
          const { roleId, name, userId, introduction, stationIds, org } = data
          // roles must be a non-empty array

          // if (!roles || roles.length <= 0) {
          //   commit('SET_ROLES', [''])
          //   // reject('此用户的角色信息不可为空')嘿嘿没有角色
          // }
          // else{
          //   commit('SET_ROLES', roles)
          // }
          commit('SET_ROLES', roleId)
          commit('SET_STATIONIDS', stationIds)
          commit('SET_NAME', name)
          commit('SET_USERID', userId)
          commit('SET_ORG', [1])
          commit('SET_INTRODUCTION', introduction)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeTokenCookies()
          removeTokenSessionStorage()
          resetRouter()
          resolve()
        })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', 0)
      removeTokenCookies()
      removeTokenSessionStorage()
      resolve()
    })
  },

  // Dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setTokenCookies(data.token)
      setTokenSessionStorage(data.token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
